const path = require('path');
const HtmlWebpackPlugin = require('html-webpack-plugin');
const CleanWebpackPlugin = require('clean-webpack-plugin');
const webpack = require('webpack');
// 定义入口文件
let entry = {};
const glob = require("glob");
let HtmlPlugin = [];

glob.sync('./src/*.html').forEach(item => {
  const filename = path.basename(item).toLowerCase();
  const chunk = filename.replace('.html', '');
  entry[chunk] = `./src/${chunk}.js`;
  HtmlPlugin.push(
    new HtmlWebpackPlugin({
      filename: filename,
      template: path.resolve(item),
      inject: 'body',
      title: 'webpack测试',
      chunks: [chunk],
      hash: true,
      minify: {
        removeAttributeQuotes: true, // 去除引号
        collapseWhitespace: false, // true代码合并成一行
      }
    })
  )
})
module.exports = {
  entry: entry,
  output: {
    path: path.join(__dirname, 'dist'),
    filename: '[name].[hash:8].js', // 会自动根据上面的name来取名字
  },
  devServer: {
    contentBase: path.join(__dirname, 'dist'),
    port: 8000,
    compress: false,
    open: true,
  },
  plugins: [
    new webpack.HotModuleReplacementPlugin(), // 热更新,每次修改后会自动刷新
    new CleanWebpackPlugin(), // 每次打包清空dist文件夹
    ...HtmlPlugin,
  ],
  module: {
    rules: [
      {
        test: /\.css$/,
        use: [
          { loader: 'style-loader' },
          { loader: 'css-loader' }
        ]
      },
      {
        test: /\.less$/,
        use: [
          { loader: 'style-loader' },
          { loader: 'css-loader' },
          { loader: 'less-loader' }
        ]
      }
    ]
  },
  resolve: {}
}